package com.lanou3g.demo;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lanou3g.demo.bean.ScoreBean;
import com.lanou3g.demo.bean.StudentBean;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class SMain {
    public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/new_db";
        String user = "root";
        String password = "root";
        Connection conn = DriverManager.getConnection(url, user, password);
        QueryRunner qr = new QueryRunner();
        String sql = "select * from t_students";
        String sql1 = "select * from t_score where stu_id = ?";

        List<StudentBean> studentBeans = qr.query(conn, sql, new BeanListHandler<>(StudentBean.class, new UnderlineProcessor()));

        for (StudentBean studentBean : studentBeans) {
            List<ScoreBean> scoreBeans = qr.query(conn, sql1, new BeanListHandler<>(ScoreBean.class, new UnderlineProcessor()), studentBean.getStuId());
            studentBean.setScores(scoreBeans);

        }
        System.out.println(studentBeans);

        Gson g = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd")
                .create();
        String s = g.toJson(studentBeans);
        FileOutputStream fos = new FileOutputStream(new File("stu.json"));
        fos.write(s.getBytes());

        fos.close();
        DbUtils.close(conn);


    }
}
